﻿#region 命名空间

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using Ext.Net;
using Ext.Net.MVC;
using Sharp.DataTransferObject;
using Sharp.Infrastructure;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.ExtNet;
using Sharp.Portal.Mvc;
using Sharp.Portal.Mvc.Form;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.Platform.Models;
using PartialViewResult = Ext.Net.MVC.PartialViewResult;

#endregion

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [System.Web.Mvc.Authorize]
    [AutomaticTemplate]
    public class RoleController : Controller
    {
        public ActionResult Index(string containerId, int? userId)
        {
            RoleIndexViewModel vm = new RoleIndexViewModel()
            {
                Simple = false,
                ItemPanelUrlAction = "UserInRole",
                ItemPanelWidth = 600
            };
            return new PartialViewResult
            {
                Model = vm,
                ContainerId = containerId,
                RenderMode = RenderMode.AddTo
            };
        }

        /// <summary>
        ///     分页数据
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ActionResult GetPaged(ExtRequestParameters parameters,int? userId)
        {
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                var page = proxy.Channel.GetRolePaged(parameters.ToPagingFeature());

                if (userId.HasValue)
                {
                    var user = proxy.Channel.GetUserByKey(userId.Value ).Data;
                    page.Data.ForEach(x =>
                    {
                        x.Selected = user.Roles.Any(r => r.Id == x.Id);
                    });
                }

                return this.Store(page.Data, page.TotalRecords);
            }
        }

        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            RoleDTO roleDto;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                roleDto = proxy.Channel.GetRoleByKey(id.Value);
            }
            if (roleDto == null)
            {
                return HttpNotFound();
            }

            return new PartialViewResult { Model = roleDto.To<RoleViewModel>() };
        }
        [Permission("新增", 1, "001003001")]
        public ActionResult Create()
        {
            return new PartialViewResult { Model = new RoleViewModel() };
        }
        [Permission("编辑", 2, "001003002")]
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            RoleDTO roleDto;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                roleDto = proxy.Channel.GetRoleByKey(id.Value);
            }
            if (roleDto == null)
            {
                return HttpNotFound();
            }
            return new PartialViewResult { Model = roleDto.To<RoleViewModel>() };
        }

        [System.Web.Mvc.HttpPost]
        public ActionResult Save(RoleViewModel role)
        {
            Result res;
            var roleDto = role.To<RoleDTO>();
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                res = proxy.Channel.SaveRole(roleDto);
            }

            return this.JsonNet(res);
        }

        [System.Web.Mvc.HttpPost]
        [Permission("删除", 3, "001003003")]
        public ActionResult Delete(int[] ids)
        {
            Result res;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                res = proxy.Channel.DeleteRoles(ids);
            }

            return this.JsonNet(res);
        }

        /// <summary>
        /// 检查角色名称是否被占用
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public ActionResult CheckName(string title)
        {
            //bool valid;
            //using (var proxy = new WebApiClientServiceProxy<IUserService>())
            //{
            //    valid = !proxy.Channel.CheckRoleName(title);
            //}
            return this.JsonNet(new { valid = true });
        }

        public ActionResult UserInRole(string id)
        {
            return new PartialViewResult
            {
                Model = new UserInRoleModel()
                {
                    Id = id,
                    StoreUrlAction = "GetPaged,User"
                },
                RenderMode = RenderMode.AddTo
            };
        }

        public ActionResult AddUserWindow(int? id)
        {
            return new PartialViewResult
            {
                ViewName = "AddUserWindow",
                Model = new UserIndexViewModel()
                {
                    Id = id.Value
                }
            };
        }
        [DirectMethod]
        public ActionResult AddUser(string userIds, int? roleId, string refreshGrid)
        {
            Result res;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                res = proxy.Channel.AssignRole(userIds.ToArrInt(), roleId.Value);
            }

            var dr = this.Direct();
            if (res.Err.Length == 0)
            {
                dr.Script = string.Format("Ext.getCmp('{0}').getStore().reload();", refreshGrid);
            }
            return dr;
        }

        //[DirectMethod]
        //public ActionResult RemoveUser(int[] userIds, int? roleId, string refreshGrid)
        //{
        //    Result res;
        //    using (var proxy = new WebApiClientServiceProxy<IUserService>())
        //    {
        //        res = proxy.Channel.UnassignRole(userIds, roleId);
        //    }

        //    var dr = this.Direct();
        //    if (res.Err.Length == 0)
        //        dr.Script = string.Format("Ext.getCmp('{0}').getStore().reload();", refreshGrid);
        //    return dr;

        //}

        /// <summary>
        /// 关联用户
        /// </summary>
        /// <param name="roleIds"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [Permission("分配角色", 3, "001003004")]
        public ActionResult Relation(int[] roleIds, int userId)
        {
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                var res = proxy.Channel.RelationUser(userId, roleIds);

                return this.JsonNet(res);
            }
        }
        public ActionResult LoadWindowForUser(int userId)
        {
            RoleIndexViewModel vm = new RoleIndexViewModel()
            {
                Simple = false,
                ItemPanelUrlAction = "UserInRole",
                ItemPanelWidth = 600
            };


            //vm.InitiallySelectedRows = new SelectedRowCollection();
            //vm.InitiallySelectedRows.Add(new SelectedRow(1));
            //using (var proxy = new WebApiClientServiceProxy<IUserService>())
            //{
            //    var user = proxy.Channel.GetUserByKey(userId).Data;

            //    vm.InitiallySelectedRows.AddRange(user.Roles.Select(x => new SelectedRow(x.Name.ToString())));
            //}

            return new PartialViewResult
            {
                ViewName = "WindowForUser",
                Model = vm
            };
        }
    }
}